This document demonstrates how to use openCyto plugin mechanism to incorporate the clustering-based gating algorithm into openCyto auto-gating framework.

Prepare the data

library(flowCore)
library(flowWorkspace)
dataDir <- system.file("extdata",package="flowWorkspaceData")
gs <- load_gs(list.files(dataDir, pattern = "gs_manual",full = TRUE))
#simplify gating tree
gs_pop_remove(gs, "CD4")
gs_pop_remove(gs, "CD8")
plot(gs)

Write a custom gating function that runs kmeans and wrap the result as a multipleFilterResult

kmeans_gating <- function(fr, pp_res = NULL, channels, ...){
    kmeans_results <- kmeans(scale(exprs(fr)[,channels]), ...)
    res <- as.factor(kmeans_results$cluster) 
    #name the sub pops properly
    levels(res) <- paste("tsub", levels(res))
    #return it as multipleFilterResult object
    as(res, "filterResult")
    
}

test it to ensure it returns the expected result

gh <- gs[[1]]
fr <- gh_pop_get_data(gh, "CD3+")
markers <- c("CD4", "CD8", "CD45RA")
channels <- sapply(markers, function(marker){
  getChannelMarker(fr, marker)$name
})

kmeans_gating(fr, channels = channels, centers = 4)
## A filterResult produced by the filter named ''
##  resulting in multiple populations:
##   tsub 1
##   tsub 2
##   tsub 3
##   tsub 4

Note that the levels of the factor will be used to tag the clustering population names.

Register it as plugin

library(openCyto)
register_plugins(fun = kmeans_gating, methodName = "tsub_gating")
## [1] TRUE

Use it in openCyto gating

gs_add_gating_method(gs
                     , alias = "*" #* means the pop names are parsed from gating results
                     , pop = "*"
                     , parent = "CD3+",
                     , dims = "CD4,CD8,CD45RA", #channels to be passed to gating function
                     , gating_method = "tsub_gating"
                     , gating_args = "centers=4, nstart=5" #arguments passed on to gating function
                     )

Visualize the result

plot(gs)

library(ggcyto)
gs_pop_get_stats(gs, node = c("singlets", "tsub 1", "tsub 2", "tsub 3", "tsub 4"))
##                     sample      pop count
## 1: CytoTrol_CytoTrol_1.fcs singlets 87022
## 2: CytoTrol_CytoTrol_1.fcs   tsub 1 21958
## 3: CytoTrol_CytoTrol_1.fcs   tsub 2  6607
## 4: CytoTrol_CytoTrol_1.fcs   tsub 3 11562
## 5: CytoTrol_CytoTrol_1.fcs   tsub 4 14356
ggcyto(gs, aes(CD45RA, CD4), subset = "CD3+") + 
    geom_gate("tsub 1", color = "red", alpha = 0.5) + 
    geom_gate("tsub 2", color = "blue", alpha = 0.5) + 
    geom_gate("tsub 3", color = "black", alpha = 0.5) +
    geom_gate("tsub 4", color = "green", alpha = 0.5)